<template>
    <div class="login-box" @keyup.enter="submitForm">
        <h2>Welcome</h2>
        <el-form ref="form" :model="form" :rules="rules">
            <el-form-item label="" prop="username">
                <el-input @blur="isShowCode" v-model.trim="form.username" placeholder="Username"></el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
                <el-input type="password" v-model.trim="form.password" placeholder="Password"></el-input>
            </el-form-item>
            <el-form-item label="" prop="code" v-if="code.isShow">
                <el-input class="code" v-model.trim="form.code" placeholder="Verification Code"></el-input>
                <img class="code-img" @click="getCode" :src="code.url" alt="">
            </el-form-item>
            <el-form-item>
                <el-button :loading="loading" type="primary" @click.prevent="submitForm">Login</el-button>
            </el-form-item>
        </el-form>
        <div class="forget">
            <router-link to="/forgetpassword">I fogot my password</router-link>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'LoginForm',
        data() {
            // 密码验证
            const checkPass = (rule, value, callback) => {
                const reg = /^\w{6,18}$/

                if (!reg.test(value)) {
                    callback(new Error())
                } else {
                    callback()
                }
            }

            return {
                loading: false,
                form: {
                    username: '',
                    password: '',
                    code: ''
                },
                oldname: '',
                code: {
                    isShow: false,
                    url: ''
                },
                rules: {
                    username: [
                        {required: true, message: 'Username/mailbox cannot be empty!', trigger: 'blur'},
                        {max: 50, message: 'Username/mailbox format error!', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: 'Password cannot be empty!', trigger: 'blur'},
                        {validator: checkPass, message: 'Password format error!', trigger: 'blur'}
                    ],
                    code: [
                        {required: true, message: 'Verification code cannot be empty!', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            // 获取验证码
            getCode() {
                this.code.url = `${this.axios.defaults.baseURL}/ForeignLogin/ForeignHadVerifyCode?username=${this.form.username}&time=${new Date().getTime()}`
            },
            // 判断是否显示验证码
            async isShowCode() {
                if (this.oldname === this.form.username) return

                this.oldname = this.form.username

                const { code } = await this.axios.get(`/ForeignLogin/ForeignHadVerifyCode?user=${this.form.username}`)

                this.code.isShow = code
                if (code) this.getCode()
            },
            // 登录
            submitForm() {
                this.$refs.form.validate(async valid => {
                    if (!valid) return

                    this.loading = true

                    const res = await this.axios.get(`/ForeignLogin/Login?username=${this.form.username}&password=${this.form.password}&verifcode=${this.form.code}`)

                    this.loading = false
                    
                    switch(res.code) {
                        // 登录成功
                        case 1:
                            if (!res.Data.editpassword) {
                                localStorage.setItem('firstLogin', res.token)
                                this.$router.push('/login/firstlogin')
                            } else {
                                localStorage.setItem('token', res.token)
                                this.$router.push('/index')
                            }
                            break
                        // 验证码错误
                        case 3:
                            this.$message.error('Verification code error!')
                            break
                        // 用户名被禁用
                        case 6:
                            this.$message.error('This user is disabled!')
                            break
                        // 用户名或密码错误
                        case 7:
                            this.$message.error('Error in username or password!')
                            break
                        // 登录失败
                        default:
                            this.$message.error('Login failed!')
                    }
                    // 是否显示验证码
                    this.code.isShow = res.showcode
                    if (res.showcode) this.getCode()
                })
            }
        }
    }
</script>

<style scoped>
    .login-box {width: 428px; background: #fff; border-radius: 5px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 0 35px;}
    h2 {font-size: 30px; text-align: center; margin: 30px auto 40px;}
    .forget {text-align: center; margin: 20px auto 22px;}
    .forget a {color: #4A90E2; font-size: 14px;}
    .code {width: 190px;}
    .code-img {width: 140px; height: 48px; float: right; cursor: pointer;}
</style>